package com.example.sdk.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.sdk.exception.MoPlusException;
import com.example.sdk.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by mobao-xi on 16/3/17.
 */
@WebFilter(urlPatterns = {"/order/*"})
public class EncryptFilter implements Filter {

    private final static String GZIPFLAG = "gzip";
    private final static String AES_KEY = "AES_KEY";
    protected static final Logger log = LoggerFactory.getLogger(EncryptFilter.class);

    @Override
    public void destroy() {
        log.info("----Destroy EncryptFilter----");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        log.info("----DoFilter EncryptFilter start----");

        EncryptServletRequest eRequest = doDecodeRequest(req, resp);
        //将返回数据进行加密
        if (eRequest != null) {
            EncryptServletResponse eResponse = new EncryptServletResponse((HttpServletResponse) resp);
            chain.doFilter(eRequest, eResponse); //如果返回值要加密则执行这个
            try {
                this.doEncodeResponse(req, eResponse);//将返回数据进行加密
            } catch (Exception e) {
                log.error("加密返回数据错误：", e);
            }
//            chain.doFilter(eRequest, resp);//返回值不加密

        } else {
            chain.doFilter(req, resp);
        }

        log.info("----DoFilter EncryptFilter end----");
    }

    private void doEncodeResponse(ServletRequest request, EncryptServletResponse response) throws Exception {
        byte[] outData = response.getContent();
        String data = new String(outData);

        log.info("RESULT:" + data);

        ReturnDTO resBean = JSON.parseObject(data, ReturnDTO.class);
        JSONObject retData = resBean.getData();
        if ("0".equalsIgnoreCase(resBean.getRetCode())) {
            retData.put("result", "0");
        }
        log.info(retData.toString());
        outData = retData.toJSONString().getBytes();
        log.info("outData : " + retData.toJSONString());
        log.info("retData: " + JSON.toJSONString(resBean.getRetData(), SerializerFeature.WriteMapNullValue));//输出值为null的字段
        //将返回结果按照按照aes方式进行加密
        String aesKey = UUIDUtils.getUUID();
        log.info("aesKey: " + aesKey);
//        byte[] encrypt = AESUtils.encrypt(retData.toJSONString(), aesKey);
        byte[] encrypt = AESUtils.encrypt(JSON.toJSONString(resBean.getRetData(), SerializerFeature.WriteMapNullValue), aesKey);
        //16进制密文 解密时要先转换 为2进制再解密
        String result = AESUtils.parseByte2HexStr(encrypt);
        log.info("result: " +result);
        String rsa_aes_key = RSAUtils.encrypt(aesKey);
        log.info("rsa 后的 aes " + rsa_aes_key);
        resBean.setAesKey(rsa_aes_key);
        resBean.setResultStr(result);
        // 输出加密内容到client
        response.output(JSON.toJSONString(resBean, SerializerFeature.WriteMapNullValue).getBytes());
    }

    private EncryptServletRequest doDecodeRequest(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;
        String ip = "127.0.0.1";
//        ip = "192.168.38.250";
        log.info("Request Scheme is " + httpReq.getScheme() + " from " + ip);
        Enumeration<?> parmas = httpReq.getParameterNames();
        Map<String, String> rquestMap = new HashMap<String, String>();
        StringBuffer requestBuf = new StringBuffer();
        String apiname = request.getParameter("apiName") == null ? "" : request.getParameter("apiName");
        while (parmas.hasMoreElements()) {
            Object object = (Object) parmas.nextElement();
            String name = object.toString();
            String value = RequestUtils.getStringParameter(httpReq, name, "");
            requestBuf.append(name + "=" + value + "&");
            rquestMap.put(name, value);
        }
        System.out.println("-------------" + requestBuf.toString());
        if (httpReq.getMethod().equalsIgnoreCase("POST")) {

            try {
                String aesKey = RSAUtils.decrypt(rquestMap.get("key"));
                System.out.println("aesKey is " + aesKey);
                AESSecProcessor processor = new AESSecProcessor(aesKey);
                processor.processWithTimestamp(rquestMap.get("dataParam").getBytes());

                log.info("REQUEST:" + processor.getData());
                Map<String, String> dataMap = convertToMap(processor.getData() + "&location=" + ip);

                Map<String, String> paramMap = new HashMap<String, String>();

                paramMap.put("data", JSON.toJSONString(dataMap));
                paramMap.put("api", dataMap.get("apiName"));
                paramMap.put("version", "0.1");

                EncryptServletRequest eRequest = new EncryptServletRequest(httpReq, dataMap);

                return eRequest;
            } catch (MoPlusException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }


        } else if (httpReq.getMethod().equalsIgnoreCase("GET")) {
            String apiName = httpReq.getParameter("method");
            log.debug("HTTP Method is GET, apiName is " + apiName);
            if (!apiName.equalsIgnoreCase("MOBO_PLUS_KB_ENCRYPTION_GET")) {
                httpResp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return null;
            }
        }
        return null;
    }


    private Map<String, String> convertToMap(String data) {
        Map<String, String> map = new HashMap<String, String>();
        String[] ps = data.split("&");
//        &tradeSummary=MuWPjOiinOWtkA==
        for (String p : ps) {
            String vs[] = p.split("=");
            map.put(vs[0], p.replace(vs[0] + "=", ""));
        }
        return map;
    }


    @Override
    public void init(FilterConfig config) throws ServletException {
        log.info("----Init EncryptFilter----");
    }
}
